package com.cygsunri.consumption.api;

import com.cygsunri.common.service.CommonDataService;
import com.cygsunri.consumption.entity.EnergyResponse;
import com.cygsunri.consumption.entity.enumerate.EnergySort;
import com.cygsunri.measurement.entity.MeasurementValue;
import com.cygsunri.rbac.entity.Account;
import com.cygsunri.rbac.service.AccountService;
import com.cygsunri.scada.service.ScadaMeasurementService;
import com.cygsunri.template.entity.psr.DeviceTemplateData;
import com.cygsunri.template.service.DeviceTemplateDataService;
import com.cygsunri.util.DateUtil;
import com.cygsunri.util.TimeUtil;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 能耗首页API(带地图)
 */
@RestController
@RequestMapping("/api/consumption/all/energy")
public class ConsumptionEnergyController {

    @Autowired
    private CommonDataService commonDataService;

    @Autowired
    private ScadaMeasurementService scadaMeasurementService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private DeviceTemplateDataService deviceTemplateDataService;

    /**
     * 今日、昨日、本月、上月能耗数据
     * @param user 用户name
     */
    @RequestMapping(value = "/comparison/values/users/{user}", method = RequestMethod.GET)
    public ResponseEntity<List<EnergyResponse>> getComparisonValues(@PathVariable("user") String user) {
        List<EnergyResponse> energyResponses = new ArrayList<>();
        Account account = accountService.getAccountByName(user);
        for (EnergySort energySort : EnergySort.values()) {
            ImmutablePair<String, Integer> pair = scadaMeasurementService.getMeasurementID(account.getPsrID(), energySort.getName());
            if (pair == null) {
                continue;
            }
            DeviceTemplateData deviceTemplateData = deviceTemplateDataService.getDeviceTemplateDataByPsrIDAndName(account.getPsrID(), energySort.getName());

            List<Double> today = new ArrayList<>();
            List<Double> lastDay = new ArrayList<>();
            List<Double> thisMonth = new ArrayList<>();
            List<Double> lastMonth = new ArrayList<>();

            MeasurementValue todayV = commonDataService.getValue(pair.getLeft(), DateUtil.nowMilliSeconds(), 500);
            if (!todayV.isInValid()) {
                today.add(todayV.getData());
            }

            MeasurementValue lastDayV = commonDataService.getValue(pair.getLeft(), DateUtil.lastDay(), 500);
            if (!lastDayV.isInValid()) {
                lastDay.add(lastDayV.getData());
            }

            MeasurementValue thisMonthV = commonDataService.getValue(pair.getLeft(), DateUtil.nowMilliSeconds(), 502);
            if (!thisMonthV.isInValid()) {
                thisMonth.add(thisMonthV.getData());
            }

            MeasurementValue lastMonthV = commonDataService.getValue(pair.getLeft(), DateUtil.lastMonth(), 502);
            if (!lastMonthV.isInValid()) {
                lastMonth.add(lastMonthV.getData());
            }

            EnergyResponse energyResponse = new EnergyResponse()
                    .setEnergyCode(energySort.getName())
                    .setEnergyDesc(energySort.getDesc())
                    .setEnergyUnit(deviceTemplateData.getUnit())
                    .setToday(today)
                    .setLastDay(lastDay)
                    .setThisMonth(thisMonth)
                    .setLastMonth(lastMonth);
            energyResponses.add(energyResponse);
        }
        return new ResponseEntity<>(energyResponses, HttpStatus.OK);
    }

    /**
     * 今日、昨日每5分钟 / 本月、上月每天  历史能耗数据
     * @param user 用户name
     */
    @RequestMapping(value = "/history/values/users/{user}", method = RequestMethod.GET)
    public ResponseEntity<List<EnergyResponse>> getHistoryValues(@PathVariable("user") String user) {
        List<EnergyResponse> energyResponses = new ArrayList<>();
        Account account = accountService.getAccountByName(user);
        for (EnergySort energySort : EnergySort.values()) {
            ImmutablePair<String, Integer> pair = scadaMeasurementService.getMeasurementID(account.getPsrID(), energySort.getName());
            if (pair == null) {
                continue;
            }
            DeviceTemplateData deviceTemplateData = deviceTemplateDataService.getDeviceTemplateDataByPsrIDAndName(account.getPsrID(), energySort.getName());

            //今日、昨日历史存盘数据
            List<Double> today = commonDataService.getHistoryValueToDouble(pair.getLeft(), DateUtil.startOfToday(), DateUtil.nowString(), 5, 2);
            List<Double> lastDay = commonDataService.getHistoryValueToDouble(pair.getLeft(), DateUtil.startOfLastDay(), DateUtil.endOfLastDay(), 5, 2);

            //本月、上月每天数据
            List<Double> thisMonth = new ArrayList<>();
            List<Double> lastMonth = new ArrayList<>();
            Integer dayOfMonth = LocalDateTime.now().getDayOfMonth();
            Integer lastMonthDays = DateUtil.getDaysOfMonth(LocalDateTime.now().minusMonths(1));
            for (int i = 1; i <= 31; i++) {
                if (i <= dayOfMonth) {
                    LocalDateTime l = LocalDateTime.now().withDayOfMonth(i);
                    MeasurementValue m = commonDataService.getValue(pair.getLeft(), TimeUtil.toMilliSeconds(l), 500);
                    if (!m.isInValid()) {
                        thisMonth.add(m.getData());
                    }
                }

                if (i <= lastMonthDays) {
                    LocalDateTime l = LocalDateTime.now().minusMonths(1).withDayOfMonth(i);
                    MeasurementValue m = commonDataService.getValue(pair.getLeft(), TimeUtil.toMilliSeconds(l), 500);
                    if (!m.isInValid()) {
                        lastMonth.add(m.getData());
                    }
                }
            }

            EnergyResponse energyResponse = new EnergyResponse()
                    .setEnergyCode(energySort.getName())
                    .setEnergyDesc(energySort.getDesc())
                    .setEnergyUnit(deviceTemplateData.getUnit())
                    .setToday(today)
                    .setLastDay(lastDay)
                    .setThisMonth(thisMonth)
                    .setLastMonth(lastMonth);
            energyResponses.add(energyResponse);
        }
        return new ResponseEntity<>(energyResponses, HttpStatus.OK);
    }
}
